<template>
  <div>
    <el-form label-width="130px" :model="form" :rules="rules" ref="inationRef">
      <div>
        <el-row style="margin-bottom: 5px" v-show="status == 0">
          <el-col :span="15"> </el-col>
          <el-col :span="2" style="line-height: 24px">
            <el-button
              size="small"
              @click="handleNext(1)"
              link
              v-if="isShow == 2"
              :disabled="!form.contractId"
              >提交评审</el-button
            >
          </el-col>
          <el-col :span="2" style="line-height: 24px">
            <el-button
              size="small"
              link
              @click="handleQuotation"
              :disabled="!form.contractId"
              >源自报价单</el-button
            >
          </el-col>
          <el-col :span="2" style="line-height: 24px">
            <el-button
              size="small"
              @click="handleNext(2)"
              link
              v-if="isShow == 3"
              :disabled="!form.contractId"
              >提交</el-button
            >
          </el-col>
          <el-col :span="3">
            <el-row justify="end">
              <el-button type="success" size="small" @click="submit(false)"
                >保存</el-button
              >
            </el-row>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同编号：">
              <onlinePreview
                :typeId="serialTypeId"
                @emitForm="emitForm"
                ref="onlinePreviewRef"
                v-if="!form.contractCode"
              >
              </onlinePreview>
              <span v-else>{{ form.contractCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称：" prop="contractName">
              <el-input
                placeholder="请输入合同名称"
                v-model="form.contractName"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="合同类型：" prop="contractType">
              <el-select
                v-model="form.contractType"
                placeholder="请选择合同类型"
                clearable
                filterable
              >
                <el-option
                  v-for="dict in sys_contract_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="紧急程度：" prop="degree">
              <el-select
                v-model="form.degree"
                placeholder="请选择紧急程度"
                clearable
                filterable
              >
                <el-option
                  v-for="dict in sys_degree"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="重大项目：" prop="projectId">
              <el-select
                v-model="form.projectId"
                placeholder="请选择重大项目"
                clearable
                filterable
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.value"
                  :label="item.label"
                  :value="parseInt(item.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员：" prop="busUser">
              <el-select
                v-model="form.busUser"
                placeholder="请选择业务员"
                clearable
                filterable
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="采样来源：" prop="sampleSource">
              <el-radio-group v-model="form.sampleSource">
                <el-radio
                  v-for="dict in sys_sample_source"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                  style="margin-right: 20px"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检后样品处置：" prop="sampleAfter">
              <el-select
                v-model="form.sampleAfter"
                placeholder="请选择检后样品处置"
                style="width: 100%"
                clearable
                filterable
              >
                <el-option
                  v-for="dict in sys_sample_handle"
                  :key="dict.value"
                  :value="dict.value"
                  :label="dict.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目负责人：" prop="projectUser">
              <el-select
                v-model="form.projectUser"
                placeholder="请选择项目负责人"
                style="width: 100%"
                clearable
                filterable
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="协商条款：" prop="xstks">
              <el-select
                v-model="form.xstks"
                placeholder="请选择协商条款"
                clearable
                style="width: 100%"
                filterable
                multiple
                collapse-tags
              >
                <el-option
                  v-for="dict in sys_xstk_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="合同开始时间：" prop="beginDate">
              <el-date-picker
                v-model="form.beginDate"
                placeholder="请选择合同开始时间"
                type="date"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="要求完成时间：" prop="requireDate">
              <el-date-picker
                v-model="form.requireDate"
                placeholder="请选择要求完成时间"
                type="date"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测目的：" prop="jcmd">
              <el-input
                placeholder="请输入检测目的"
                v-model="form.jcmd"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="当前合同状态：" prop="orgEmail"
              >编辑中</el-form-item
            >
          </el-col> -->
        </el-row>
      </div>
      <!-- 委托单位信息 -->
      <div>
        <el-row>
          <p class="pinformation">委托单位信息</p>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="委托单位名称：" prop="wtCustomName">
              <el-autocomplete
                v-model="form.wtCustomName"
                :fetch-suggestions="wtQuerySearch"
                clearable
                maxlength="100"
                @select="autocompleteWtSelect"
                style="width: 100%"
                placeholder="请输入委托单位名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人：" prop="wtContacts">
              <el-input
                maxlength="20"
                clearable
                placeholder="请输入联系人"
                v-model="form.wtContacts"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话：" prop="wtPhonenumber">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入联系电话"
                v-model="form.wtPhonenumber"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="委托地区：" prop="wtAddress">
              <City
                @areaCode="wtAreaCode"
                :id="'right'"
                ref="wtAreaRef"
                @queryParam="queryParam"
                :viewForm="wtCityForm"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="委托单位地址：" prop="wtAddress">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入委托单位地址"
                v-model="form.wtAddress"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="报告领取方式：" prop="wtReportType">
              <el-select v-model="form.wtReportType" placeholder="请选择报告领取方式">
                <el-option
                  v-for="dict in sys_report_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电子邮箱：" prop="wtEmail">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入电子邮箱"
                v-model="form.wtEmail"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <!-- 受检单位信息 -->
      <div>
        <el-row style="margin-bottom: 5px">
          <el-col :span="3">
            <p class="pinformation">受检单位信息</p>
          </el-col>
          <el-col :span="4"> </el-col>
          <el-col :span="4">
            <el-button type="success" size="small" @click="sameUnit" v-show="status == 0"
              >同委托单位</el-button
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="受检单位名称：" prop="sjCustomName">
              <el-autocomplete
                v-model="form.sjCustomName"
                :fetch-suggestions="sjQuerySearch"
                clearable
                maxlength="100"
                @select="autocompleteSjSelect"
                style="width: 100%"
                placeholder="请输入委托单位名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人：" prop="sjContacts">
              <el-input
                maxlength="20"
                clearable
                placeholder="请输入联系人"
                v-model="form.sjContacts"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话：" prop="sjPhonenumber">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入联系电话"
                v-model="form.sjPhonenumber"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="受检地区：" prop="wtAddress">
              <City
                @areaCode="sjAreaCode"
                :id="'right'"
                ref="wtAreaRef"
                :viewForm="sjCityForm"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="受检单位地址：" prop="sjAddress">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入受检单位地址"
                v-model="form.sjAddress"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div>
        <el-row style="margin-bottom: 5px; height: 25px">
          <el-col :span="2">
            <p class="pinformation">合同文档生成</p>
          </el-col>
          <el-col :span="2">
            <p
              style="
                font-size: 14px;
                margin-top: 0px;
                margin-bottom: 6px;
                font-weight: 500;
              "
            >
              共 {{ form.contractFileList.length }} 条数据
            </p>
          </el-col>
          <!-- <el-col :span="2">
            <el-button link icon="Plus" type="success" @click="upLoadClick('contract')"
              v-show="status == 0">上传</el-button>
          </el-col> -->
          <el-col
            :span="8"
            style="margin-top: -5px"
            v-if="templateList.length > 0 && status == 0"
          >
            <el-form-item label="合同模板：" prop="userName">
              <el-select
                size="small"
                v-model="form.templateId"
                style="width: 100%"
                placeholder="请选择"
              >
                <el-option
                  v-for="template in templateList"
                  :key="template.templateId"
                  :label="template.templateName"
                  :value="template.templateId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :span="2"
            style="margin-left: 10px"
            v-if="templateList.length > 0"
          >
            <el-button
              type="success"
              size="small"
              v-show="form.contractId"
              @click="handleExportWord"
              >生成合同</el-button
            >
          </el-col>
        </el-row>
        <el-table :data="form.contractFileList">
          <el-table-column label="文件名称" align="center">
            <template #default="scope">
              <span
                @click="proxy.$download.localFile(scope.row.fileId, scope.row.fileName)"
                class="fileNameHover"
                >{{ scope.row.fileName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="上传时间" align="center" prop="uploadTime" />
          <el-table-column label="上传人" align="center" prop="createBy" />
          <el-table-column label="操作" align="center" v-if="status == 0">
            <template #default="scope">
              <el-button link type="success" @click="handleContractFile(scope.row)"
                >编辑</el-button
              >
              <el-button link type="success" @click="handleDelContractFile(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <el-row style="margin-bottom: 5px">
          <el-col :span="3">
            <p class="pinformation">客户合同附件</p>
          </el-col>
          <el-col :span="3">
            <p
              style="
                font-size: 14px;
                margin-top: 0px;
                margin-bottom: 6px;
                font-weight: 500;
              "
            >
              共 {{ form.customFileList.length }} 条数据
            </p>
          </el-col>
          <el-col :span="2">
            <el-button
              link
              icon="Plus"
              type="success"
              @click="upLoadClick('custom')"
              v-show="status == 0"
              >上传</el-button
            >
          </el-col>
        </el-row>
        <el-table :data="form.customFileList">
          <el-table-column label="文件编号" align="center" prop="fileCode" />
          <el-table-column label="文件名称" align="center" prop="fileMc">
            <template #default="scope">
              <span
                @click="proxy.downloadFile(scope.row.fileList, 'local')"
                class="fileNameHover"
                >{{ scope.row.fileMc }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="上传时间" align="center" prop="createTime" />
          <el-table-column label="上传人" align="center" prop="createUserName" />
          <el-table-column label="操作" align="center" v-if="status == 0">
            <template #default="scope">
              <el-button link type="success" @click="editFileClick(scope.row)"
                >编辑</el-button
              >
              <el-button link type="success" @click="DeleteBtnClick(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <el-dialog
      :class="'el-dialog-theme3'"
      v-model="fileOpen"
      :title="fileTitle"
      @close="closeDialog"
    >
      <el-form :disabled="disabled" :model="fileForm" :rules="fileRules" ref="fileRef">
        <el-form-item label="文件名称：" prop="fileMc" label-width="85">
          <el-input v-model="fileForm.fileMc" clearable></el-input>
        </el-form-item>
        <el-form-item label="文件编号：" prop="fileCode" label-width="85">
          <el-input v-model="fileForm.fileCode" clearable></el-input>
        </el-form-item>
        <fileUpload v-model="fileForm.fileList"></fileUpload>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="save">保存</el-button>
          <el-button type="danger" @click="fileOpen = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="quotationOpen"
      title="源自报价单"
      @close="closedDialog"
      width="600"
    >
      <el-form label-width="70" :model="quotationForm" :rules="formRules" ref="formRef">
        <el-form-item label="报价单：" prop="priceId">
          <el-select
            v-model="quotationForm.priceId"
            clearable
            filterable
            remote
            reserve-keyword
            remote-show-suffix
            :remote-method="remoteMethod"
            :loading="loading"
            style="width: 100%"
          >
            <el-option
              v-for="item in quotationList"
              :key="item.priceId"
              :value="item.priceId"
              :label="item.priceCode + '　' + item.priceName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="quotationSave">确 定</el-button>
          <el-button type="danger" @click="quotationOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="confirmOpen"
      title="确认业务信息"
      @close="closedConfirm"
      width="60%"
    >
      <el-form :model="queryParams" label-width="85px" ref="queryRef">
        <el-row>
          <el-col :span="5">
            <el-form-item label="检测类别：" prop="jclbId">
              <el-select
                filterable
                clearable
                v-model="queryParams.jclbId"
                @change="handleQuery"
              >
                <el-option
                  v-for="item in jclbTypeList"
                  :key="item.jclbId"
                  :value="item.jclbId"
                  :label="item.jclbName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="点位名称：" prop="pointName">
              <el-input
                v-model="queryParams.pointName"
                placeholder="请输入点位名称"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="周期类型：" prop="cycleType">
              <el-select v-model="queryParams.cycleType" filterable @change="handleQuery">
                <el-option
                  v-for="dict in sys_point_cycle"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="success" style="margin-left: 10px" @click="handleQuery"
              >搜索</el-button
            >
            <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation">点位列表</p>
        <p class="totalStyle">共{{ total }}条数据</p>
      </el-row>
      <el-table v-loading="pointTableLoading" :data="pointList" height="350px">
        <el-table-column label="检测类别" align="center" prop="jclbName" width="200" />
        <el-table-column label="点位名称" align="center" prop="pointName" />
        <el-table-column label="连测天数" align="center" prop="sampleDay" width="80" />
        <el-table-column label="每天频次" align="center" prop="sampleCount" width="80" />
        <el-table-column label="周期" align="center" width="70px">
          <template #default="scope">
            <dict-tag :options="sys_point_cycle" :value="scope.row.cycleType" />
          </template>
        </el-table-column>
        <el-table-column label="周期次数" align="center" prop="cycleCount" width="80" />
        <el-table-column label="检测项目数" align="center" prop="jcxmCount" width="100" />
        <el-table-column
          label="分包项目数"
          align="center"
          prop="jcxmPCount"
          width="100"
        />
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="queryPointList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-row style="justify-content: end">
            <div style="color: red; line-height: 32px; margin-right: 10px">
              请核实业务信息是否正确!
            </div>
            <el-button type="success" @click="handleNext" :disabled="countdown > 0">{{
              buttonText
            }}</el-button>
            <el-button type="danger" @click="confirmOpen = false">取 消</el-button>
          </el-row>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import City from "@/components/City/index.vue";
import useRouteView from "@/store/modules/routeView";
import onlinePreview from "@/components/onlinePreview/index.vue";
import { getCurrentUser, getLatestProcess } from "@/api/common";

import {
  addContract,
  contractOption,
  listUser,
  getContract,
  tjContract,
  getQuotationList,
  quotationSubmit,
  verify,
  queryTemplateList,
  getFile,
  delContractFileId,
} from "@/api/contract/check";
import { allListJclb } from "@/api/store/jclb";
import {
  getFileListAPI,
  addFileItemAPI,
  queryFileItemInfo,
  deleteFileItem,
} from "@/api/resource/instrumentItem";
import { listPoint } from "@/api/contract/taskPoint";

import { getCustom } from "@/api/contract/custom";
import { getToken } from "@/utils/auth";
const router = useRouter();
const route = useRoute();

const routeViewStore = useRouteView();

const { proxy } = getCurrentInstance();

const {
  sys_degree,
  sys_xstk_type,
  sys_sample_source,
  sys_report_type,
  sys_sample_handle,
  sys_point_cycle,
} = proxy.useDict(
  "sys_xstk_type",
  "sys_degree",
  "sys_sample_source",
  "sys_report_type",
  "sys_sample_handle",
  "sys_point_cycle"
);
const { sys_contract_type } = proxy.useOrgDict("sys_contract_type");
const projectList = ref([
  { value: 0, label: "否" },
  { value: 1, label: "是" },
]);

const props = defineProps({
  echo: {
    type: String,
  },
  status: {
    type: Number,
  },
  isShow: {
    type: Number,
  },
  taskId: {
    type: String,
  },
});
const status = ref(props.status);
const isShow = ref(props.isShow);
const serialTypeId = ref(0);
const fileTitle = ref("");
const wtAreaRef = ref(null);
const onlinePreviewRef = ref(null);
const templateList = ref([]);
const data = reactive({
  form: {
    degree: 2,
    projectId: 0,
    sampleSource: 1,
    contractFileList: [],
    customFileList: [],
    params: {},
    wtReportType: 1,
    xstks: ["1"],
    sampleAfter: "0",
  },
  formRules: {
    priceId: [{ required: true, message: "报价单不能为空", trigger: "blur" }],
  },
  queryParams: {
    pageSize: 10,
    pageNum: 1,
  },
  rules: {
    contractName: [{ required: true, message: "合同名称不能为空", trigger: "blur" }],
    beginDate: [{ required: true, message: "合同开始时间不能为空", trigger: "blur" }],
    sjCustomId: [{ required: true, message: "受检单位名称不能为空", trigger: "blur" }],
    projectUser: [{ required: true, message: "项目负责人不能为空", trigger: "blur" }],
    // wtCustomName: [
    //   { required: true, message: "委托单位不能为空", trigger: "blur" },
    // ],
    // wtContacts: [
    //   { required: true, message: "联系人不能为空", trigger: "blur" },
    // ],
    // wtPhonenumber: [
    //   { required: true, message: "联系电话不能为空", trigger: "blur" },
    // ],
    // wtReportType: [
    //   { required: true, message: "报告领取方式不能为空", trigger: "blur" },
    // ],
    contractType: [{ required: true, message: "合同类型不能为空", trigger: "blur" }],
    projectId: [{ required: true, message: "重大项目不能为空", trigger: "blur" }],
    sampleSource: [{ required: true, message: "采样来源不能为空", trigger: "blur" }],
  },
  fileRules: {
    fileMc: [{ required: true, message: "文件名称不能为空", trigger: "blur" }],
  },
});

const { form, rules, queryParams, fileRules, formRules } = toRefs(data);

const sameUnit = () => {
  form.value.sjCustomName = form.value.wtCustomName;
  form.value.sjCustomId = form.value.wtCustomId;
  form.value.sjAddress = form.value.wtAddress;
  form.value.sjContacts = form.value.wtContacts;
  form.value.sjPhonenumber = form.value.wtPhonenumber;
  form.value.sjAreaCode = form.value.wtAreaCode;
  sjCityForm.value = JSON.parse(JSON.stringify(cityInfor.value));
};

watch(
  () => route,
  (newVal) => {
    if (newVal.path == "/flowable/task/record/index") {
      const { path, name, meta } = newVal;
      routeViewStore.setRouteView1({ path, name, meta });
    }
  }
);

watch(
  () => sys_contract_type.value,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      resultContractType();
    }
  }
);

watch(
  () => props.status,
  (newVal) => {
    status.value = newVal;
  }
);

watch(
  () => props.isShow,
  (newVal) => {
    isShow.value = newVal;
  }
);

function resultContractType() {
  const defaultItem = sys_contract_type.value.filter((item) => item.isDefault == "Y");
  if (defaultItem && defaultItem.length > 0) {
    form.value.contractType = defaultItem[0].value;
  }
}
function reset() {
  nextTick(() => {
    proxy.resetForm("inationRef");
    proxy.$refs["inationRef"].clearValidate();
    delete form.value.status;
    delete form.value.contractId;
    delete form.value.templateId;
    delete form.value.contractCode;
    wtCityForm.value = {};
    sjCityForm.value = {};
    form.value.contractFileList = [];
    form.value.customFileList = [];
    serialTypeId.value = 0;
    form.value.params["serialData"] = undefined;
    delete form.value.sjAreaCode;
    delete form.value.sjCityCode;
    delete form.value.sjCityName;
    delete form.value.sjProvinceCode;
    delete form.value.wtAreaCode;
    delete form.value.wtCityCode;
    delete form.value.wtCityName;
    delete form.value.wtProvinceCode;

    delete form.value.sjCustomId;
    delete form.value.wtCustomId;

    form.value.projectUser = currentUser.value;
    nextTick(() => {
      onlinePreviewRef.value.reset();
      onlinePreviewRef.value.getList();
    });
    resultContractType();
  });
}

const wtCityForm = ref({});
const sjCityForm = ref({});
function echo(copy) {
  nextTick(() => {
    getContract(props.echo).then((res) => {
            form.value = res.data;
      form.value.xstks = form.value.xstk ? form.value.xstk.split(",") : [];
      form.value.contractFileList = [];
      form.value.customFileList = [];
      serialTypeId.value = 0;
      if (!form.value.templateId && templateList.value.length == 1) {
        form.value.templateId = templateList.value[0].templateId;
      }
      form.value.params = {};
      if(copy){
        form.value.params["isCopy"] = copy;
      }
      wtCityForm.value = {
        provinceCode: form.value.wtProvinceCode,
        cityCode: form.value.wtCityCode,
        areaCode: form.value.wtAreaCode,
      };
      sjCityForm.value = {
        provinceCode: form.value.sjProvinceCode,
        cityCode: form.value.sjCityCode,
        areaCode: form.value.sjAreaCode,
      };
      handleQueryContractFile();
      // 查询客户文件
      getFileListAPI({ groupId: form.value.contractId, fileType: 26 }).then((res) => {
        form.value.customFileList = res.data;
      });
      nextTick(() => {
        onlinePreviewRef.value.reset();
        onlinePreviewRef.value.getList();
      });
    });
    proxy.$refs["inationRef"].clearValidate();
  });
}

function handleQueryContractFile(wordId) {
  form.value.contractFileList = [];
  if (wordId) {
    proxy.$modal.msgSuccess("保存成功！");
    form.value.wordId = wordId;
  }
  // 查询合同文档
  if (form.value.wordId) {
    getFile(form.value.wordId).then((res) => {
      form.value.contractFileList.push(res.data);
    });
  }
}
function save() {
  if (fileForm.value.fileList.length) {
    proxy.$refs["fileRef"].validate((valid) => {
      if (valid) {
        addFileItemAPI(fileForm.value).then((res) => {
          fileOpen.value = false;
          if (fileForm.value.fileType == 25) {
            getFileListAPI({
              groupId: form.value.contractId,
              fileType: 25,
            }).then((res) => {
              form.value.contractFileList = res.data;
            });
          } else {
            getFileListAPI({
              groupId: form.value.contractId,
              fileType: 26,
            }).then((res) => {
              form.value.customFileList = res.data;
            });
          }
        });
      }
    });
  } else {
    proxy.$modal.msgError("请选择要上传的文件");
  }
}

const emits = defineEmits(["renovate"], ["clickAdd"]);

function submit(isAuto) {
  return new Promise((resolve, reject) => {
    proxy.$refs["inationRef"].validate((valid) => {
      if (valid) {
        if (!form.value.contractId && !form.value.params["serialData"]) {
          proxy.$modal.msgError("合同编号不能为空");
          reject();
          return false;
        }
        form.value.xstk = form.value.xstks?.join(",");
        addContract(form.value)
          .then((res) => {
            if (!isAuto) {
              proxy.$modal.msgSuccess(res.msg);
            }
            if (!form.value.contractId) {
              form.value.contractCode = form.value.params["serialData"].maxCode;
              form.value.contractId = res.data;
            }
            emits("renovate", res.data);
            resolve("success");
          })
          .catch(() => {
            reject("false");
          });
      } else {
        reject("false");
      }
    });
  });
}

const wtQuerySearch = (querySearch, cb) => {
  let results = [];
  form.value.wtCustomId = "";
  contractOption({ customName: querySearch, pageName: 1, pageSize: 10 }).then((res) => {
    results = res.rows.map((item) => {
      if (querySearch === item.customName) {
        form.value.wtCustomId = item.customId;
        form.value.wtContacts = item.contactsName;
        form.value.wtPhonenumber = item.contactsPhonenumber;
        form.value.wtEmail = item.email;
        form.value.wtAddress = item.address;
        wtCityForm.value = {
          provinceCode: item.provinceCode,
          cityCode: item.cityCode,
          areaCode: item.areaCode,
        };
        form.value.wtAreaCode = item.areaCode;
      }
      return { value: item.customName, customId: item.customId };
    });
    cb(results);
  });
};

const sjQuerySearch = (querySearch, cb) => {
  let results = [];
  form.value.sjCustomId = "";
  contractOption({ customName: querySearch, pageName: 1, pageSize: 10 }).then((res) => {
    results = res.rows.map((item) => {
      if (querySearch === item.customName) {
        form.value.sjCustomId = item.customId;
        form.value.sjContacts = item.contactsName;
        form.value.sjPhonenumber = item.contactsPhonenumber;
        form.value.sjEmail = item.email;
        form.value.sjAddress = item.address;
        sjCityForm.value = {
          provinceCode: item.provinceCode,
          cityCode: item.cityCode,
          areaCode: item.areaCode,
        };
        form.value.sjAreaCode = item.areaCode;
      }
      return { value: item.customName, customId: item.customId };
    });
    cb(results);
  });
};

function autocompleteWtSelect(row) {
  form.value.wtCustomId = row.customId;
  getCustom(row.customId).then((res) => {
    form.value.wtContacts = res.data.contactsName;
    form.value.wtPhonenumber = res.data.contactsPhonenumber;
    form.value.wtEmail = res.data.email;
    form.value.wtAddress = res.data.address;
    wtCityForm.value = {
      provinceCode: res.data.provinceCode,
      cityCode: res.data.cityCode,
      areaCode: res.data.areaCode,
    };
    form.value.wtAreaCode = res.data.areaCode;
  });
}

function autocompleteSjSelect(row) {
  form.value.sjCustomId = row.customId;
  getCustom(row.customId).then((res) => {
    form.value.sjContacts = res.data.contactsName;
    form.value.sjPhonenumber = res.data.contactsPhonenumber;
    form.value.sjAddress = res.data.address;
    sjCityForm.value = {
      provinceCode: res.data.provinceCode,
      cityCode: res.data.cityCode,
      areaCode: res.data.areaCode,
    };
    form.value.sjAreaCode = res.data.areaCode;
  });
}

const currentUser = ref();
const userList = ref([]);
listUser().then((res) => {
  userList.value = res.data;
  // getCurrentUser().then((res) => {
  //   console.log("1:{}",res.data)
  //   form.value.projectUser = res.data;
  //   currentUser.value = res.data;
  // });
});

queryTemplateList().then((res) => {
  if (res.data) {
    templateList.value = res.data;
    if (templateList.value.length == 1) {
      form.value.templateId = templateList.value[0].templateId;
    }
  } else {
    templateList.value = [];
  }
});
function wtAreaCode(val) {
  form.value.wtAreaCode = val;
}

const cityInfor = ref({});
function queryParam(val) {
  cityInfor.value = val;
}

function sjAreaCode(val) {
  form.value.sjAreaCode = val;
}

const fileOpen = ref(false);
const fileForm = ref({
  fileList: [],
});

function upLoadClick(name) {
  submit(true).then((res) => {
    fileOpen.value = true;
    disabled.value = false;
    fileForm.value.groupId = form.value.contractId;
    if (name == "contract") {
      fileTitle.value = "上传合同文档";
      fileForm.value.fileType = 25;
    } else {
      fileTitle.value = "上传客户合同附件";
      fileForm.value.fileType = 26;
    }
  });
}

function handleExportWord() {
  if (!form.value.contractId) {
    proxy.$modal.msgError("请先保存合同！");
    return;
  }
  if (!form.value.templateId) {
    proxy.$modal.msgError("请选择合同模板！");
    return;
  }
  // proxy.$modal.loading("正在生成合同，请稍候...");
  let testParam = getToken() + "φpageOffice";
  POBrowser.openWindow(
    "/contract/word?contractId:" +
      form.value.contractId +
      "&templateId:" +
      form.value.templateId,
    "fullscreen=yes;",
    testParam
  );
}
const disabled = ref(false);
function editFileClick(row) {
  queryFileItemInfo(row.dataId).then((res) => {
    fileForm.value = res.data;
    fileOpen.value = true;
    disabled.value = false;
    fileTitle.value = "编辑文件";
  });
}

function handleContractFile(row) {
  let testParam = getToken() + "φpageOffice";
  POBrowser.openWindow(
    "/contract/word?fileId:" + row.fileId + "&fileName:" + row.fileName,
    "fullscreen=yes;",
    testParam
  );
}

const handleDelContractFile = async (row) => {
  proxy.$modal
    .confirm("是否确认删除此合同？")
    .then(async function () {
      await delContractFileId(form.value.contractId, row.fileId).then(() => {
        proxy.$modal.msgSuccess("删除成功");
        form.value.contractFileList = [];
        delete form.value.wordId;
      });
    })
    .catch(() => {});
};

const DeleteBtnClick = async (row) => {
  proxy.$modal
    .confirm("是否确认删除此数据项？")
    .then(async function () {
      await deleteFileItem([row.dataId]).then(() => {
        proxy.$modal.msgSuccess("删除成功");
        getFileListAPI({
          groupId: form.value.contractId,
          fileType: row.fileType,
        }).then((res) => {
          if (row.fileType == 25) {
            form.value.contractFileList = res.data;
          } else {
            form.value.customFileList = res.data;
          }
        });
      });
    })
    .catch(() => {});
};

function emitForm(val) {
  debugger;
  form.value.params["serialData"] = val;
}

function closeDialog() {
  fileForm.value = {
    fileList: [],
  };
  proxy.$refs["fileRef"].clearValidate();
}

function startProcess() {
  if (!form.value.wtCustomName) {
    proxy.$modal.msgError("委托单位名称不能为空！");
    return;
  }
  if (!form.value.wtContacts) {
    proxy.$modal.msgError("联系人不能为空！");
    return;
  }
  if (!form.value.wtPhonenumber) {
    proxy.$modal.msgError("联系电话不能为空！");
    return;
  }
  if (!form.value.wtReportType) {
    proxy.$modal.msgError("报告领取方式不能为空！");
    return;
  }
  submit(true).then((res) => {
    verify(form.value.contractId).then((resp) => {
      if (resp.code != 200) {
        proxy.$modal.msgError(resp.msg);
        return;
      }
      if (routeViewStore.routeView1) {
        proxy.$tab.closePage(routeViewStore.routeView1);
      }
      proxy.$modal.loading("正在启动流程中，请稍候...");
      confirmOpen.value = false;
      if (props.taskId) {
        const taskId = props.taskId;
        proxy.$tab.closePage().then(() => {
          router.push({
            path: "/flowable/task/record/index",
            query: {
              taskId: taskId,
              finished: true,
              path: "/contract/check",
              v_contractId: form.value.contractId,
            },
          });
        });
        proxy.$modal.closeLoading();
        return;
      }
      getLatestProcess({ category: "1" }).then((res) => {
        proxy.$modal.closeLoading();
        if (res.data) {
          proxy.$tab.closePage().then(() => {
            router.push({
              path: "/flowable/task/record/index",
              query: {
                deployId: res.data.deploymentId,
                finished: true,
                path: "/contract/check",
                v_contractId: form.value.contractId,
              },
            });
          });
        } else {
          proxy.$modal.msgError("流程启动失败，未到找到相关流程！");
        }
      });
    });
  });
}
watch(
  () => fileForm.value.fileList,
  () => {
    if (fileForm.value.fileList.length > 0) {
      fileForm.value.fileMc = fileForm.value.fileList[0].fileName;
    } else {
      fileForm.value.fileMc = "";
    }
  }
);

function tjSave() {
  verify(form.value.contractId).then((resp) => {
    if (resp.code != 200) {
      proxy.$modal.msgError(resp.msg);
      return;
    }
    proxy.$modal.confirm("确定要提交当前合同吗？").then(function () {
      if (!form.value.wtCustomName) {
        proxy.$modal.msgError("委托单位名称不能为空！");
        return;
      }
      if (!form.value.wtContacts) {
        proxy.$modal.msgError("联系人不能为空！");
        return;
      }
      if (!form.value.wtPhonenumber) {
        proxy.$modal.msgError("联系电话不能为空！");
        return;
      }
      if (!form.value.wtReportType) {
        proxy.$modal.msgError("报告领取方式不能为空！");
        return;
      }
      submit(true).then(() => {
        tjContract(form.value.contractId).then((res) => {
          proxy.$modal.msgSuccess("提交成功");
          confirmOpen.value = false;
          emits("clickAdd");
        });
      });
    });
  });
}

const quotationForm = ref({});
const quotationOpen = ref(false);
const loading = ref(false);
const quotationList = ref([]);

function handleQuotation() {
  quotationOpen.value = true;
  quotationForm.value = {};
}

function remoteMethod(val) {
  if (val) {
    loading.value = true;
    setTimeout(() => {
      getQuotationList({ priceCode: val }).then((res) => {
        loading.value = false;
        quotationList.value = res.rows;
      });
    }, 200);
  } else {
    quotationList.value = [];
  }
}

function quotationSave() {
  proxy.$refs["formRef"].validate((valid) => {
    if (!valid) return;
    quotationSubmit(form.value.contractId, quotationForm.value.priceId).then((res) => {
      proxy.$modal.msgSuccess("保存成功");
      quotationOpen.value = false;
      echo();
    });
  });
}

function closedDialog() {
  quotationForm.value = {};
}

defineExpose({
  reset,
  echo,
  submit,
});

const confirmOpen = ref(false);
const isSave = ref(0);
const pointTableLoading = ref(false);
const total = ref(0);
const pointList = ref([]);
const buttonText = ref("继 续");
const countdown = ref(11);
function confirm(isSave1) {
  confirmOpen.value = true;
  startCountdown();
  getJclbTypeList();
  queryPointList();
  isSave.value = isSave1;
}

const timer = ref(null);

function startCountdown() {
  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value === 0) {
      clearInterval(timer.value);
      buttonText.value = "继 续";
    } else {
      buttonText.value = `继 续（${countdown.value}）`;
    }
  }, 1000);
}

function handleNext(isSubmit) {
  isSave.value = isSubmit;
  if (isSave.value == 1) {
    startProcess();
  } else if (isSave.value == 2) {
    tjSave();
  }
}
// 获取点位列表数据
function queryPointList() {
  pointTableLoading.value = true; // 开启加载
  // 根据客户id查询点位列表
  queryParams.value.primaryId = form.value.contractId;
  listPoint(queryParams.value).then((res) => {
    pointList.value = res.rows; // 保存点位列表
    total.value = res.total;
    pointTableLoading.value = false; // 关闭加载
  });
}
function closedConfirm() {
  clearInterval(timer.value);
  total.value = 0;
  buttonText.value = "继 续";
  countdown.value = 11;
  pointList.value = [];
  jclbTypeList.value = [];
  isSave.value == 0;
  queryParams.value = {
    pageSize: 10,
    pageNum: 1,
  };
}
const jclbTypeList = ref([]);
function getJclbTypeList() {
  allListJclb({ typeId: 1 }).then((res) => {
    jclbTypeList.value = res.data;
  });
}
function handleQuery() {
  queryPointList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageSize: 10,
    pageNum: 1,
  };
  queryParams.value.primaryId = form.value.contractId;
  handleQuery();
}

onMounted(() => {
  nextTick(() => {
    window.handleQueryContractFile = handleQueryContractFile;
  });
});
</script>

<style></style>
